<script setup lang="ts">
import { Message, TableColumn } from "@arco-design/web-vue";
import { onMounted, reactive, ref, h } from "vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import { standardDelete, standardList, getSum } from "@/services/scoreApi.ts";
import type { ScoreListType } from "@/types/scoreType.ts";
import useModal from "@/hooks/useModal.ts";
import ScoreModal from "@/pages/review/score/ScoreModal.vue";
import { reviewModuleListModule } from "@/services/reviewModuleApi.ts";
import type { ReviewModuleListModuleItemType } from "@/types/reviewModuleType.ts";
const { ModalShow, ModalHide } = useModal();

const loading = reactive({
  search: false,
  reset: false,
  table: false,
});

const scoreModalRef = ref<{
  init: () => void;
  edit: (record: { name: string; id: string }) => void;
}>();

const data = ref<ScoreListType[]>([]);

const moduleList = ref<ReviewModuleListModuleItemType[]>([]);

const moduleId = ref<string>("");

const getList = () => {
  loading.table = true;
  standardList({
    moduleId: moduleId.value,
  })
    .then((res) => {
      if (res.code === 200) {
        data.value = res.data;
      } else {
        data.value = [];
      }
    })
    .finally(() => {
      loading.table = false;
      getSumInfo();
    });
};
const sum = ref("");
const getSumInfo = () => {
  getSum({
    moduleId: moduleId.value,
  }).then((res) => {
    sum.value = res.data;
  });
};

const handleAdd = () => {
  scoreModalRef.value?.init();
};

const handleEdit = (record: ScoreListType) => {
  scoreModalRef.value?.edit(record);
};

const handleDelete = (record: ScoreListType) => {
  ModalShow({
    content: "确认要删除当前的评分标准吗？",
  }).then(() => {
    standardDelete(record.id)
      .then((res) => {
        if (res.code === 200) Message.success("删除成功");
        else Message.error(res.msg);
      })
      .finally(() => {
        getList();
        ModalHide();
      });
  });
};

onMounted(() => {
  reviewModuleListModule()
    .then((res) => {
      moduleList.value = res.data;
      moduleId.value = res.data[0].id;
    })
    .finally(getList);
  // getList();
});

function formatLevel1TextWithBoldIntro(text: string) {
  // 判断是否以编号开头（如 1.、2.）
  // const startsWithNumber = /^\d+\./.test(text);

  const startsWithNumber = /^[1-9]\d*\./.test(text);

  if (startsWithNumber) {
    // 如果以编号开头，只换行，不加粗
    return text.replace(/(\d+\..*?)(?=\d+\.|$)/gs, "<br>$1").trim();
  }

  // 否则，加粗开头部分，换行编号部分
  const regex = /^([^\d]+?)(?=\d+\.)/s;
  const match = text.match(regex);

  if (match) {
    const [, intro] = match;
    const numberedContent = text.substring(intro.length).trim();
    const formattedNumberedContent = numberedContent.replace(
      /(\d+\..*?)(?=\d+\.|$)/gs,
      "<br>$1"
    );
    return `<strong style="font-size: 15px;">${intro.trim()}</strong>${formattedNumberedContent}`;
  }

  if (text.includes("0.5分")) {
    console.log(111);
    return text;
  }

  // 如果没有编号，只加粗并换行
  return `<strong>${text}</strong><br>`;
}

const columns: TableColumn[] = [
  {
    title: "序号",
    slotName: "index",
    align: "center",
    width: 80,
  },
  {
    title: "一级指标",
    key: "name",
    dataIndex: "name",
    align: "center",
    width: 150,
  },
  {
    title: "分值",
    key: "level1",
    dataIndex: "level1",
    align: "center",
    width:100
  },
  {
    title: "指标描述",
    dataIndex: "level2",
    render: ({ record }) => {
      return h("div", {
        innerHTML: formatLevel1TextWithBoldIntro(record.level2),
      });
    },
  },
  // {
  //   title: "分值",
  //   key: "standardScore",
  //   dataIndex: "standardScore",
  //   align: "center",
  //   width: 100,
  // },
  {
    title: "操作",
    slotName: "operate",
    align: "center",
    width: 200,
    fixed: "right",
  },
];

const spanMethodAll = ({ column, rowIndex, record }) => {
  if (column.dataIndex === "name") {
    const prevRecord = rowIndex > 0 ? data.value[rowIndex - 1].name : null;
    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameCount = data.value.filter(
        (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }

  if (column.dataIndex === "level1") {
    const prevRecord = rowIndex > 0 ? data.value[rowIndex - 1] : null;
    if (
      prevRecord &&
      prevRecord.name === record.name &&
      prevRecord.level1 === record.level1
    ) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameAndLevel1Count = data.value.filter(
        (item) => item.name === record.name && item.level1 === record.level1
      ).length;
      return { rowspan: sameNameAndLevel1Count, colspan: 1 };
    }
  }

  return { rowspan: 1, colspan: 1 };
};

const handleTabChange = () => {
  getList();
};
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-tabs
        v-model:active-key="moduleId"
        @change="handleTabChange"
        type="card"
      >
        <a-tab-pane
          v-for="item in moduleList"
          :key="item.id"
          :title="item.moduleName"
        >
          <div class="tabletools">
            <a-space>
              <a-button
                type="outline"
                @click="handleAdd"
              >新增</a-button>
              总分{{ sum }}
            </a-space>
          </div>
          <a-table
            :loading="loading.table"
            :data="data"
            :columns="columns"
            :bordered="tableBorder"
            :pagination="false"
            :span-method="spanMethodAll"
          >
            <template #index="{rowIndex}">
              {{rowIndex + 1 }}
            </template>
            <template #operate="{record}">
              <a-space>
                <a-button
                  type="primary"
                  @click="handleEdit(record)"
                >编辑</a-button>
                <a-button
                  type="primary"
                  status="danger"
                  @click="handleDelete(record)"
                >删除</a-button>
              </a-space>
            </template>
          </a-table>

        </a-tab-pane>
      </a-tabs>
    </a-card>
    <ScoreModal
      ref="scoreModalRef"
      @refresh="getList"
      :moduleId="moduleId"
    />
  </a-space>
</template>

<style scoped lang="scss">
.container {
  padding: 20px;
}

.tabletools {
  margin-bottom: 20px;
}
:deep(.arco-tabs-pane) {
  box-sizing: border-box;
  padding: 10px !important;
}
</style>
